import React, { useState, useContext } from "react";
import {
  View,
  TouchableOpacity,
  StyleSheet,
  Text,
  Platform,
  TextInput,
  Alert,
  ScrollView,
} from "react-native";
import LoadingBar from "../../components/InterView/LoadingBar";
import * as Animatable from "react-native-animatable";
import { AntDesign } from "@expo/vector-icons";
import { Feather } from "@expo/vector-icons";
import { FontAwesome } from "@expo/vector-icons";
import { FontAwesome5 } from "@expo/vector-icons";
import { MaterialIcons } from "@expo/vector-icons";
import query from "../../api/query";

const ForgetPasswordScreen = ({ navigation }) => {
  const [isLoading, setIsLoading] = useState(false);
  const roles = ["调研员", "管理员", "审核员"]; //0 1 2
  const [selected, setSelected] = useState(0);
  const [account, setAccount] = useState("");
  const [name, setName] = useState("");
  const [group, setGroup] = useState("");
  const [password, setPassword] = useState("");
  const [confirm_password, setConfirmPassword] = useState("");
  const [secureTextEntry, setSecureTextEntry] = useState(true);
  const [confirmSecureTextEntry, setConfirmSecureTextEntry] = useState(true);
  const [error, setError] = useState(false);

  const onConfirm = () => {
    Alert.alert("提示", "确定提交吗？", [
      {
        text: "取消",
      },
      {
        text: "确定",
        onPress: async () => {
          if (
            account.length == 0 ||
            password.length == 0 ||
            name.length == 0 ||
            confirm_password == 0
          ) {
            Alert.alert("提示", "输入内容不能为空", [{ text: "确定" }]);
            return;
          }
          if (selected !== 2 && group.length === 0) {
            Alert.alert("提示", "输入内容不能为空", [{ text: "确定" }]);
            return;
          }
          if (password !== confirm_password) {
            Alert.alert("提示", "两次输入密码不一致", [{ text: "确定" }]);
            return;
          }
          try {
            setIsLoading(true);
            let role;
            if (selected == 0) {
              role = "user";
            } else if (selected == 1) {
              role = "admin";
            } else {
              role = "auditor";
            }
            let mygroup;
            if (selected == 2) {
              mygroup = "";
            } else {
              mygroup = group;
            }
            let item = {
              role: role,
              account: account,
              name: name,
              group: mygroup,
              newPassword: password,
            };
            console.log("=====", item);
            await query.patch("/user/forgetPassword", item);
            Alert.alert("提示", "重置密码成功", [
              {
                text: "确定",
                onPress: () => {
                  setIsLoading(false);
                  navigation.goBack();
                },
              },
            ]);
          } catch (err) {
            setIsLoading(false);
            Alert.alert("提示", "重置密码失败,请检查原始账号信息填写是否正确");
            console.log("重置密码失败", err.message);
          }
        },
      },
    ]);
  };

  return (
    <View style={styles.container}>
      <LoadingBar visible={isLoading} />
      <View style={styles.header}>
        <Text style={styles.text_header}>忘记密码</Text>
      </View>
      <Animatable.View style={styles.footer} animation="fadeInUpBig">
        <ScrollView style={{ paddingHorizontal: 20, flex: 1 }}>
          <Text style={{ color: "#aaa", textAlign: "center", marginTop: 20 }}>
            请输入原始账号信息
          </Text>
          <Text style={styles.text_footer}>账号</Text>
          <View style={styles.action}>
            <FontAwesome5 name="user-alt" size={16} color="#05375a" />
            <TextInput
              placeholder="请输入原始账号"
              style={styles.textInput}
              value={account}
              onChangeText={(val) => {
                setAccount(val);
              }}
            />
          </View>

          <Text style={[styles.text_footer, { marginTop: 10 }]}>姓名</Text>
          <View style={styles.action}>
            <AntDesign name="carryout" size={18} color="#05375a" />
            <TextInput
              placeholder="请输入原始姓名"
              style={styles.textInput}
              value={name}
              onChangeText={(val) => setName(val)}
            />
          </View>

          <Text style={[styles.text_footer, { marginTop: 10 }]}>角色</Text>
          <View
            style={{
              flexDirection: "row",
              justifyContent: "space-around",
              marginTop: 10,
            }}
          >
            {roles.map((item, index) => {
              return (
                <TouchableOpacity
                  key={index}
                  onPress={() => setSelected(index)}
                >
                  <Text
                    style={index === selected ? styles.selectedTag : styles.tag}
                  >
                    {item}
                  </Text>
                </TouchableOpacity>
              );
            })}
          </View>

          {selected !== 2 && (
            <>
              <Text style={[styles.text_footer, { marginTop: 10 }]}>组号</Text>
              <View style={styles.action}>
                <MaterialIcons name="group" size={20} color="#05375a" />
                <TextInput
                  placeholder="请输入原始组号"
                  style={styles.textInput}
                  value={group}
                  onChangeText={(val) => setGroup(val)}
                />
              </View>
            </>
          )}

          <Text style={{ color: "#aaa", textAlign: "center", marginTop: 20 }}>
            请输入新密码
          </Text>
          <Text style={[styles.text_footer, { marginTop: 10 }]}>密码</Text>
          <View style={styles.action}>
            <FontAwesome name="lock" color="#05375a" size={18} />
            <TextInput
              placeholder="请输入新密码"
              style={styles.textInput}
              value={password}
              secureTextEntry={secureTextEntry ? true : false}
              onChangeText={(val) => {
                setPassword(val);
                let iserror = false;
                if (val !== confirm_password) {
                  iserror = true;
                }
                setError(iserror);
              }}
            />
            <TouchableOpacity
              onPress={() =>
                setSecureTextEntry((pre) => setSecureTextEntry(!pre))
              }
            >
              {secureTextEntry ? (
                <Feather name="eye-off" color="gray" size={18} />
              ) : (
                <Feather name="eye" color="gray" size={18} />
              )}
            </TouchableOpacity>
          </View>

          <Text style={[styles.text_footer, { marginTop: 10 }]}>确认密码</Text>
          <View style={styles.action}>
            <FontAwesome name="lock" color="#05375a" size={18} />
            <TextInput
              placeholder="请确认你的密码"
              style={styles.textInput}
              value={confirm_password}
              secureTextEntry={confirmSecureTextEntry ? true : false}
              onChangeText={(val) => {
                setConfirmPassword(val);
                let iserror = false;
                if (val !== password) {
                  iserror = true;
                }
                setError(iserror);
              }}
            />
            <TouchableOpacity
              onPress={() =>
                setConfirmSecureTextEntry((pre) =>
                  setConfirmSecureTextEntry(!pre)
                )
              }
            >
              {confirmSecureTextEntry ? (
                <Feather name="eye-off" color="gray" size={18} />
              ) : (
                <Feather name="eye" color="gray" size={18} />
              )}
            </TouchableOpacity>
          </View>
          {error ? (
            <Text style={styles.errorMsg}>两次输入密码不一致</Text>
          ) : null}

          <View style={styles.button}>
            <TouchableOpacity style={styles.signUp} onPress={() => onConfirm()}>
              <Text style={styles.textSignUp}>提交</Text>
            </TouchableOpacity>
          </View>
        </ScrollView>
      </Animatable.View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#780808",
  },
  header: {
    flex: 1,
    justifyContent: "flex-end",
    paddingHorizontal: 20,
    paddingBottom: 50,
  },
  footer: {
    flex: 3.5,
    backgroundColor: "#fff",
    borderTopLeftRadius: 30,
    borderTopRightRadius: 30,
  },
  text_header: {
    color: "#fff",
    fontWeight: "bold",
    fontSize: 30,
  },
  text_footer: {
    color: "#05375a",
    fontSize: 16,
  },
  action: {
    flexDirection: "row",
    marginTop: 10,
    borderBottomWidth: 1,
    borderBottomColor: "#f2f2f2",
    paddingBottom: 5,
  },
  actionError: {
    flexDirection: "row",
    marginTop: 10,
    borderBottomWidth: 1,
    borderBottomColor: "#FF0000",
    paddingBottom: 5,
  },
  textInput: {
    flex: 1,
    marginTop: Platform.OS === "ios" ? 0 : -12,
    paddingLeft: 10,
    color: "#05375a",
  },
  errorMsg: {
    marginTop: 10,
    color: "#FF0000",
    fontSize: 14,
  },
  button: {
    alignItems: "center",
    marginTop: 25,
  },
  signUp: {
    backgroundColor: "#A80108",
    width: "100%",
    height: 50,
    justifyContent: "center",
    alignItems: "center",
    borderRadius: 10,
    marginBottom: 20,
  },
  signIn: {
    borderColor: "#009387",
    borderWidth: 1,
    marginTop: 15,
    width: "100%",
    height: 50,
    justifyContent: "center",
    alignItems: "center",
    borderRadius: 10,
  },
  textSignUp: {
    fontSize: 18,
    fontWeight: "bold",
    color: "#fff",
  },
  textSignIn: {
    fontSize: 18,
    fontWeight: "bold",
    color: "#05375a",
  },
  selectedTag: {
    borderWidth: 1,
    borderColor: "#A80108",
    padding: 1,
    paddingLeft: 10,
    paddingRight: 10,
    borderRadius: 2,
    color: "#A80108",
  },
  tag: {
    borderWidth: 1,
    borderColor: "#d1d1d6",
    padding: 1,
    paddingLeft: 10,
    paddingRight: 10,
    borderRadius: 10,
    color: "#d1d1d6",
    fontSize: 14,
  },
});
export default ForgetPasswordScreen;
